package ar.com.visualAORE.view;

import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Observable;
import java.util.Observer;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.Highlighter;

import org.jdesktop.swingx.VerticalLayout;

import ar.com.visualAORE.controller.DocumentViewController;
import ar.com.visualAORE.controller.ReqInternalFrameController;
import ar.com.visualAORE.controller.VersionControlFrameController;
import ar.com.visualAORE.exceptions.SaveDocumentsLayersException;
import ar.com.visualAORE.framework.controller.Controller;
import ar.com.visualAORE.framework.model.Model;
import ar.com.visualAORE.model.Concern;
import ar.com.visualAORE.model.Document;
import ar.com.visualAORE.model.ModelVisualAORE;
import ar.com.visualAORE.util.BrowserLauncher;
import ar.com.visualAORE.util.MyHtml2Text;
import ar.com.visualAORE.util.ReaderWriter;
import ar.com.visualAORE.util.ToasterMessage;


/**
 * @author Brainrain
 */
public class VisualDesktopFrame extends JFrame implements Observer{
	/**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JFileChooser fc;
	private Model model;
	private DocumentViewController controller;
	//For the Concern selected
	private Concern currentCocnern;
	private String action="";
	protected Highlighter.HighlightPainter painter;
	private String currentDocumentName;
	ReqInternalFrame rif;
	Document document;

	public VisualDesktopFrame(Model model, Controller controller) {
		initComponents();
		this.model = model;
		this.controller = (DocumentViewController)controller;
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.model.addObserver(this);
		ToasterMessage.showMessage("Welcome to the Visual AORE Assistant");
	}
	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		ModelVisualAORE model = (ModelVisualAORE) o;
		
		Concern lastConcern = model.getConcerns().get(model.getConcerns().size() - 1);
		JButton b = new JButton();
		b.setText(lastConcern.getName());
		b.setBackground(lastConcern.getColor());
		b.addActionListener(new ActionConcernButton(lastConcern));
		
		panelConcerns.add(b);
		panelConcerns.repaint();
		scrollConcerns.validate();
		this.repaint();
		
	}
	//For the Button's Action
	private class ActionConcernButton implements ActionListener{
		Concern c;
		public ActionConcernButton(Concern c){
			this.c = c;
			action = "concern";
		}
		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			System.out.println(c.getName());
			lblSelectedConcern.setText("Selected: " + c.getName());
			currentCocnern = c;
			action = "concern";
		}
	}
	private void jMenuOpenActionPerformed(ActionEvent e) {
		ToasterMessage.showMessage("Open a document to start the demarcation process");
		this.rif = new ReqInternalFrame(this, new ReqInternalFrameController(this.model));
		rif.getRadioButtonText().setSelected(true);
		desktopPane1.add(rif);
		
		//Create a file chooser
        fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML", "htm", "HTM", "html");
        fc.setFileFilter(filter);
        //Handle open button action.
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
        	 String text = ReaderWriter.readFile(fc.getSelectedFile().getPath());
        	 String textNew = ReaderWriter.readFile(fc.getSelectedFile().getPath().concat(".last"));
             String frameTitle = fc.getSelectedFile().getName();
        	
           // File file = fc.getSelectedFile();
            File concernLayer = new File(fc.getSelectedFile().getPath().concat(".xml"));
     
      
            //Imprimir solo el texto
            MyHtml2Text parser = new MyHtml2Text();
            try {
                parser.parse(new StringReader(text));
            } catch (IOException ee) {
              //handle exception
            }
            System.out.println(parser.getText());
      
             
           //Completa el ReqInternalFrame 
           rif.getTextView().setText(text);
           rif.getTextView().setCaretPosition(0);
           rif.mapControls(false);
           rif.setTitle(frameTitle);
           
    
           File versionFile = new File(fc.getSelectedFile().getPath().concat(".last"));
            //Verificamos que exista una version anterior del documento y su correspondiente concernLayer
            if(versionFile.exists() && concernLayer.exists()){
            	this.document = controller.openDocument(fc.getSelectedFile().getPath().concat(".xml"));
            	VersionControlFrameController versionController = new VersionControlFrameController(this.model);
            	VersionControlFrame vcf = new VersionControlFrame(this, versionController);
            	
           /* 	//Para el JTextPane que tiene la version guardada del documento(.last)
            	vcf.getJtextPaneLastDocumentSaved().setContentType(reqContent); 
            	vcf.getJtextPaneLastDocumentSaved().setText(textNew);
            	vcf.setTitle(frameTitle);
            	vcf.getJtextPaneLastDocumentSaved().setCaretPosition(0);
            	
                //Para el jtextPane que tiene el nuevo documento 
            	vcf.getJtextPaneNewDocument().setContentType(reqContent); 
            	vcf.getJtextPaneNewDocument().setText(text);
            	vcf.setTitle(frameTitle);
            	vcf.getJtextPaneNewDocument().setCaretPosition(0);
            	*/
            	
            	
            	
					BrowserLauncher.openURL("/home/julian/Downloads/daisydiff-1.1/daisydiff.htm");
				
            	
            	//Para el diff
            	vcf.getJtextPaneDifferences().setText(versionController.diff(fc.getSelectedFile().getPath().concat(".last"), fc.getSelectedFile().getPath()));
          
            	vcf.applyDocumentLayer(document);
            }
           	//To check if the concern's layer exist
            else if(concernLayer.exists()){
            	
           		System.out.println("El fichero " + fc.getSelectedFile().getPath().concat(".xml") + " existe");
           		Document document = controller.openDocument(fc.getSelectedFile().getPath().concat(".xml"));
           		rif.applyDocumentLayer(document, 0);
           	}
           	else{
           	  System.out.println("No tiene el xml asociado");
           	//Agrega un documento en el modelo pasando como parametros: 
           	  	//El nombre del archivo, su localizacion y el tamaño total del documento
           	this.controller.addDocument(new Document(fc.getSelectedFile().getName(),fc.getSelectedFile().getPath(), rif.getTextView().getText().length(), rif.getTextViewPanel().getLineNumber(rif.getTextView(),rif.getTextView().getText().length())));
           	System.out.println(fc.getSelectedFile().getPath());
           	//Seteo el nombre del documento seleccionado
           	this.currentDocumentName = fc.getSelectedFile().getName();
           	}
        } else {
        	desktopPane1.remove(rif);
        	this.repaint();
        	//System.out.println("Open command cancelled by user." + newline);
        }

	}
	//OLD
	/*private void jMenuOpenActionPerformed(ActionEvent e) {
		ToasterMessage.showMessage("Open a document to start the demarcation process");
		//Creo el internal frame
		this.rif = new ReqInternalFrame(this, new ReqInternalFrameController(this.model));
		rif.getRadioButtonText().setSelected(true);
		desktopPane1.add(rif);
		try {
			rif.setSelected(true);
		} catch (PropertyVetoException e1) {
			e1.printStackTrace();
		}
		//Create a file chooser
        fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML", "htm", "HTM", "html");
        fc.setFileFilter(filter);
        //Handle open button action.
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
        	 String text = ReaderWriter.readFile(fc.getSelectedFile().getPath());
        	 String textNew = ReaderWriter.readFile(fc.getSelectedFile().getPath().concat(".last"));
             String frameTitle = fc.getSelectedFile().getName();
        	
           // File file = fc.getSelectedFile();
            File concernLayer = new File(fc.getSelectedFile().getPath().concat(".xml"));
            
            
            String reqContent = "text/html";
           //Completa el ReqInternalFrame 
           rif.getJtextPane().setContentType(reqContent); 
           rif.getJtextPane().setText(text);
           Style style = rif.getJtextPane().addStyle("Red", null);
           StyleConstants.setForeground(style, Color.red);
           
           rif.getJtextPane().setCaretPosition(0);
           
           rif.mapControls(false);
           rif.setTitle(frameTitle);
    
           File versionFile = new File(fc.getSelectedFile().getPath().concat(".last"));
            //Verificamos que exista una version anterior del documento y su correspondiente concernLayer
            if(versionFile.exists() && concernLayer.exists()){
            	this.document = controller.openDocument(fc.getSelectedFile().getPath().concat(".xml"));
            	VersionControlFrameController versionController = new VersionControlFrameController(this.model);
            	VersionControlFrame vcf = new VersionControlFrame(this, versionController);
            	
            	//Para el JTextPane que tiene la version guardada del documento(.last)
            	vcf.getJtextPaneLastDocumentSaved().setContentType(reqContent); 
            	vcf.getJtextPaneLastDocumentSaved().setText(textNew);
            	vcf.setTitle(frameTitle);
            	vcf.getJtextPaneLastDocumentSaved().setCaretPosition(0);
            	
                //Para el jtextPane que tiene el nuevo documento 
            	vcf.getJtextPaneNewDocument().setContentType(reqContent); 
            	vcf.getJtextPaneNewDocument().setText(text);
            	vcf.setTitle(frameTitle);
            	vcf.getJtextPaneNewDocument().setCaretPosition(0);
            	
            	
            	
            	
					BrowserLauncher.openURL("/home/julian/Downloads/daisydiff-1.1/daisydiff.htm");
				
            	
            	//Para el diff
            	vcf.getJtextPaneDifferences().setText(versionController.diff(fc.getSelectedFile().getPath().concat(".last"), fc.getSelectedFile().getPath()));
          
            	vcf.applyDocumentLayer(document);
            }
           	//To check if the concern's layer exist
            else if(concernLayer.exists()){
            	
           		System.out.println("El fichero " + fc.getSelectedFile().getPath().concat(".xml") + " existe");
           		Document document = controller.openDocument(fc.getSelectedFile().getPath().concat(".xml"));
           		rif.applyDocumentLayer(document);
           	}
           	else{
           	  System.out.println("No tiene el xml asociado");
           	//Agrega un documento en el modelo pasando como parametros: 
           	  	//El nombre del archivo, su localizacion y el tamaño total del documento
           	this.controller.addDocument(new Document(fc.getSelectedFile().getName(),fc.getSelectedFile().getPath(), rif.getJtextPane().getText().length(), rif.getLineNumber(rif.getJtextPane(),rif.getJtextPane().getText().length())));
           	System.out.println(fc.getSelectedFile().getPath());
           	//Seteo el nombre del documento seleccionado
           	this.currentDocumentName = fc.getSelectedFile().getName();
           	}
        } else {
        	desktopPane1.remove(rif);
        	this.repaint();
        	//System.out.println("Open command cancelled by user." + newline);
        }
	}
*/	
	public Concern getCurrentCocnern() {
		return currentCocnern;
	}
	public String getAction(){
		return this.action;
	}
	public Highlighter.HighlightPainter getPainter() {
		return painter;
	}
	public void setPainter(Highlighter.HighlightPainter painter) {
		this.painter = painter;
	}
	private void jMenuSaveActionPerformed(ActionEvent e) {
	    	 try {
				this.controller.saveDocumentsLayers();
				JOptionPane.showMessageDialog(this, "The files were saved successfully", "Save documents layers", JOptionPane.PLAIN_MESSAGE);
			} catch (SaveDocumentsLayersException e1) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this, "One or more document layer file could not be saved", "Error", JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
			}
	}

	private void btnAddConcernActionPerformed(ActionEvent e) {
		// TODO add your code here
		if(txtConcern.getText().isEmpty()){
			JOptionPane.showMessageDialog(this, "The name can not be empty");
		}
		else
			new ColorChooser(txtConcern, model);
	}

	private void jMenuItemCloseAllActionPerformed(ActionEvent e) {
		// TODO add your code here
		 JInternalFrame[] frms = desktopPane1.getAllFrames();
	        for (int i = 0; i < frms.length; i++) {
	            frms[i].dispose();
	            try {
	                frms[i].setClosed(true);
	            } catch ( PropertyVetoException e1 ) {}               
	        }
	        ReqInternalFrame.inset = 0;
	    //    configurarOpciones(false);    	
	}

	private void jMenuExitActionPerformed(ActionEvent e) {
		System.exit(0);
	}

	private void buttonEraserActionPerformed(ActionEvent e) {
		// TODO add your code here
		action = "eraser";
		this.lblSelectedConcern.setText("Selected: " + action);
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		// Generated using JFormDesigner Evaluation license - Julian Rousselot
		ResourceBundle bundle = ResourceBundle.getBundle("locale");
		menuBar1 = new JMenuBar();
		menu1 = new JMenu();
		jMenuOpen = new JMenuItem();
		jMenuSave = new JMenuItem();
		jMenuItemCloseAll = new JMenuItem();
		jMenuExit = new JMenuItem();
		menu2 = new JMenu();
		menu5 = new JMenu();
		menuItem1 = new JMenuItem();
		menuItem2 = new JMenuItem();
		menu3 = new JMenu();
		menu4 = new JMenu();
		toolBar2 = new JToolBar();
		panel1 = new JPanel();
		txtConcern = new JTextField();
		btnAddConcern = new JButton();
		button2 = new JButton();
		lblSelectedConcern = new JLabel();
		scrollPane3 = new JScrollPane();
		scrollConcerns = new JScrollPane();
		panelConcerns = new JPanel();
		buttonEraser = new JButton();
		desktopPane1 = new JDesktopPane();

		//======== this ========
		setMinimumSize(new Dimension(600, 400));
		setIconImage(new ImageIcon(getClass().getResource("/icons/icon.jpg")).getImage());
		setTitle(bundle.getString("this.title"));
		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== menuBar1 ========
		{

			//======== menu1 ========
			{
				menu1.setText("File");

				//---- jMenuOpen ----
				jMenuOpen.setText("Open");
				jMenuOpen.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						jMenuOpenActionPerformed(e);
					}
				});
				menu1.add(jMenuOpen);

				//---- jMenuSave ----
				jMenuSave.setText("Save");
				jMenuSave.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						jMenuSaveActionPerformed(e);
					}
				});
				menu1.add(jMenuSave);

				//---- jMenuItemCloseAll ----
				jMenuItemCloseAll.setText(bundle.getString("jMenuItemCloseAll.text"));
				jMenuItemCloseAll.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						jMenuItemCloseAllActionPerformed(e);
					}
				});
				menu1.add(jMenuItemCloseAll);

				//---- jMenuExit ----
				jMenuExit.setText("Exit");
				jMenuExit.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						jMenuExitActionPerformed(e);
					}
				});
				menu1.add(jMenuExit);
			}
			menuBar1.add(menu1);

			//======== menu2 ========
			{
				menu2.setText("Concerns");
			}
			menuBar1.add(menu2);

			//======== menu5 ========
			{
				menu5.setText("View");

				//---- menuItem1 ----
				menuItem1.setText("Document");
				menu5.add(menuItem1);

				//---- menuItem2 ----
				menuItem2.setText("text");
				menu5.add(menuItem2);
			}
			menuBar1.add(menu5);

			//======== menu3 ========
			{
				menu3.setText("HTML");
			}
			menuBar1.add(menu3);

			//======== menu4 ========
			{
				menu4.setText("About");
			}
			menuBar1.add(menu4);
		}
		setJMenuBar(menuBar1);

		//======== toolBar2 ========
		{
			toolBar2.setOrientation(SwingConstants.VERTICAL);
			toolBar2.setMinimumSize(new Dimension(200, 324));
			toolBar2.setMaximumSize(new Dimension(200, 200));
			toolBar2.setPreferredSize(new Dimension(150, 150));

			//======== panel1 ========
			{
				panel1.setBorder(new TitledBorder("Toolbox"));
				panel1.setPreferredSize(new Dimension(45, 135));
				panel1.setMinimumSize(new Dimension(150, 345));
				panel1.setAlignmentX(0.0F);
				panel1.setAlignmentY(0.0F);

				// JFormDesigner evaluation mark
				panel1.setBorder(new javax.swing.border.CompoundBorder(
					new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
						"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
						javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
						java.awt.Color.red), panel1.getBorder())); panel1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});

				panel1.setLayout(null);

				//---- txtConcern ----
				txtConcern.setPreferredSize(new Dimension(4, 10));
				txtConcern.setMinimumSize(new Dimension(4, 10));
				panel1.add(txtConcern);
				txtConcern.setBounds(10, 25, 125, 36);

				//---- btnAddConcern ----
				btnAddConcern.setPreferredSize(new Dimension(150, 10));
				btnAddConcern.setIcon(new ImageIcon(getClass().getResource("/icons/plusS.png")));
				btnAddConcern.setBackground(Color.white);
				btnAddConcern.setToolTipText(bundle.getString("btnAddConcern.toolTipText"));
				btnAddConcern.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						btnAddConcernActionPerformed(e);
					}
				});
				panel1.add(btnAddConcern);
				btnAddConcern.setBounds(5, 85, 40, 40);

				//---- button2 ----
				button2.setIcon(new ImageIcon(getClass().getResource("/icons/trashS.png")));
				button2.setBackground(Color.white);
				button2.setToolTipText(bundle.getString("button2.toolTipText"));
				panel1.add(button2);
				button2.setBounds(95, 85, 40, 40);

				//---- lblSelectedConcern ----
				lblSelectedConcern.setText("Selected: ");
				lblSelectedConcern.setBackground(new Color(51, 255, 0));
				panel1.add(lblSelectedConcern);
				lblSelectedConcern.setBounds(5, 140, 140, 20);

				//======== scrollPane3 ========
				{

					//======== scrollConcerns ========
					{
						scrollConcerns.setBorder(new TitledBorder("Concerns"));
						scrollConcerns.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

						//======== panelConcerns ========
						{
							panelConcerns.setMinimumSize(new Dimension(0, 0));
							panelConcerns.setLayout(new VerticalLayout(10));
						}
						scrollConcerns.setViewportView(panelConcerns);
					}
					scrollPane3.setViewportView(scrollConcerns);
				}
				panel1.add(scrollPane3);
				scrollPane3.setBounds(0, 160, 140, 180);

				//---- buttonEraser ----
				buttonEraser.setIcon(new ImageIcon(getClass().getResource("/icons/goma.png")));
				buttonEraser.setBackground(Color.white);
				buttonEraser.setToolTipText(bundle.getString("buttonEraser.toolTipText"));
				buttonEraser.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						buttonEraserActionPerformed(e);
					}
				});
				panel1.add(buttonEraser);
				buttonEraser.setBounds(50, 85, 40, 40);

				{ // compute preferred size
					Dimension preferredSize = new Dimension();
					for(int i = 0; i < panel1.getComponentCount(); i++) {
						Rectangle bounds = panel1.getComponent(i).getBounds();
						preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
						preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
					}
					Insets insets = panel1.getInsets();
					preferredSize.width += insets.right;
					preferredSize.height += insets.bottom;
					panel1.setMinimumSize(preferredSize);
					panel1.setPreferredSize(preferredSize);
				}
			}
			toolBar2.add(panel1);
		}
		contentPane.add(toolBar2, BorderLayout.EAST);
		contentPane.add(desktopPane1, BorderLayout.CENTER);
		pack();
		setLocationRelativeTo(getOwner());
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	// Generated using JFormDesigner Evaluation license - Julian Rousselot
	private JMenuBar menuBar1;
	private JMenu menu1;
	private JMenuItem jMenuOpen;
	private JMenuItem jMenuSave;
	private JMenuItem jMenuItemCloseAll;
	private JMenuItem jMenuExit;
	private JMenu menu2;
	private JMenu menu5;
	private JMenuItem menuItem1;
	private JMenuItem menuItem2;
	private JMenu menu3;
	private JMenu menu4;
	private JToolBar toolBar2;
	private JPanel panel1;
	private JTextField txtConcern;
	private JButton btnAddConcern;
	private JButton button2;
	private JLabel lblSelectedConcern;
	private JScrollPane scrollPane3;
	private JScrollPane scrollConcerns;
	private JPanel panelConcerns;
	private JButton buttonEraser;
	private JDesktopPane desktopPane1;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
}
